1. 题目

有一个二维矩阵 A 其中每个元素的值为 0 或 1 。

移动是指选择任一行或列,并转换该行或列中的每一个值:将所有 0 都更改为 1,将所有 1 都更改为 0。

在做出任意次数的移动后,将该矩阵的每一行都按照二进制数来解释,矩阵的得分就是这些数字的总和。

返回尽可能高的分数。

示例: 输入:[[0,0,1,1],[1,0,1,0],[1,1,0,0]] 输出:39 解释: 转换为 [[1,1,1,1],[1,0,0,1],[1,1,1,1]] 0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39

提示:

1 <= A.length <= 20 1 <= A[0].length <= 20 A[i][j] 是 0 或 1

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/score-after-flipping-matrix 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题思路

对于行来说,越靠前比重越大,只要每行的最前一个数为0,就将它整行翻转。(2n>2n1+2n2++12^n > 2^{n-1}+2^{n-2}+\dots+1

对于列来说,每一列的每个数比重一样,看0的数量和1的数量即可,若0的数量大于1的数量就整列翻转。

最后按要求求和。

3. 代码

class Solution {
public:
    int matrixScore(vector<vector<int>>& A) {
        int row = A.size(), col = row==0?0:A[0].size();
        vector<int> cnt(col,0);
        //行
        for(int i=0; i<row; ++i){
            if(!A[i][0]) for(auto &x: A[i]) x=x^1; 
            for(int j=0; j<col; ++j){
                if(!A[i][j]) cnt[j]++;
            }
        }
        //列
        for(int i=0; i<col; ++i){
            if(cnt[i]>(float)row/2) 
            for(int j=0; j<row; ++j) A[j][i]=1^A[j][i];

        }
        //求和
        int res = 0; 
        for(int i=0; i<row; ++i){
            for(int j=0; j<col; ++j){
                res += A[i][j]*(1<<(col-j-1));
            }
        }
        return res;
    }
};

results matching ""

    No results matching ""